package com.example.mahao_final.UI

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.mahao_final.R
import com.example.mahao_final.dao.BlogDao
import com.example.mahao_final.database.BlogDatabase
import kotlinx.coroutines.launch


class BlogEditActivity : AppCompatActivity() {

    private lateinit var blogDao: BlogDao
    private lateinit var etTitle: EditText
    private lateinit var etDescription: EditText
    private lateinit var etContent: EditText
    private lateinit var btnSave: Button
    private var blogId: Long = 0

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_blog_edit)

        blogDao = BlogDatabase.getDatabase(this).blogDao()

        etTitle = findViewById(R.id.et_title)
        etDescription = findViewById(R.id.et_description)
        etContent = findViewById(R.id.et_content)
        btnSave = findViewById(R.id.btn_save)

        // 获取传递过来的博客 ID
        blogId = intent.getLongExtra("BLOG_ID", 0)

        // 加载博客数据
        loadBlogData()

        btnSave.setOnClickListener {
            saveBlog()
        }
    }

    private fun loadBlogData() {
        lifecycleScope.launch {
            val blog = blogDao.getBlogById(blogId)
            blog?.let {
                etTitle.setText(it.title)          // 设置标题
                etDescription.setText(it.description) // 设置描述
                etContent.setText(it.content)      // 设置内容
            }
        }
    }

    private fun saveBlog() {
        val title = etTitle.text.toString()
        val description = etDescription.text.toString()
        val content = etContent.text.toString()

        if (title.isNotBlank() && description.isNotBlank() && content.isNotBlank()) {
            lifecycleScope.launch {
                // 从数据库获取原始博客对象
                val existingBlog = blogDao.getBlogById(blogId)

                // 确保博客存在
                existingBlog?.let {
                    // 创建一个新的博客对象，只更新标题、描述、内容
                    val updatedBlog = it.copy(title = title, description = description, content = content)

                    // 更新数据库中的博客数据
                    blogDao.updateBlog(updatedBlog)

                    // 保存完成后，直接返回 MyBlogFragment 界面并刷新数据
                    val intent = Intent()
                    intent.putExtra("BLOG_ID", updatedBlog.id)  // 将更新的博客 ID 传递给 MyBlogFragment
                    setResult(RESULT_OK, intent)  // 通过 setResult() 传递结果
                    finish()  // 保存完成后关闭当前 Activity
                }
            }
        }
    }

}

